package com.ruoyi.web.controller.system;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.StringId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ModuleBorrow;
import com.ruoyi.system.service.IModuleBorrowService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 借阅管理Controller
 *
 * @author ruoyi
 * @date 2023-06-05
 */
@RestController
@RequestMapping("/system/borrow")
public class ModuleBorrowController extends BaseController {
    private static final String FILE_PATH = "lastIncrement.txt";
    private static final String DATE_FORMAT = "yyyyMMdd";
    @Autowired
    private IModuleBorrowService moduleBorrowService;

    /**
     * 查询借阅管理列表
     */
    // @PreAuthorize("@ss.hasPermi('system:borrow:list')")
    @GetMapping("/list")
    public TableDataInfo list(ModuleBorrow moduleBorrow) {
        startPage();
        List<ModuleBorrow> list = moduleBorrowService.selectModuleBorrowList(moduleBorrow);
        return getDataTable(list);
    }

    // @PreAuthorize("@ss.hasPermi('system:borrow:list')")
    @GetMapping("/listMore")
    public TableDataInfo listMore(ModuleBorrow ModuleBorrow) {
        startPage();
        List<ModuleBorrow> list = moduleBorrowService.selectModuleBorrowListMore(ModuleBorrow);
        return getDataTable(list);
    }

    // @PreAuthorize("@ss.hasPermi('system:borrow:list')")
    @GetMapping("/listUser")
    public TableDataInfo listMore(SysUser SysUser) {
        startPage();
        List<ModuleBorrow> list = moduleBorrowService.selectModuleBorrowListUser(SysUser);
        return getDataTable(list);
    }

    /**
     * 导出借阅管理列表
     */
    // @PreAuthorize("@ss.hasPermi('system:borrow:export')")
    @Log(title = "借阅管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ModuleBorrow moduleBorrow) {
        List<ModuleBorrow> list = moduleBorrowService.selectModuleBorrowList(moduleBorrow);
        ExcelUtil<ModuleBorrow> util = new ExcelUtil<ModuleBorrow>(ModuleBorrow.class);
        util.exportExcel(response, list, "借阅管理数据");
    }

    /**
     * 获取借阅管理详细信息
     */
    // @PreAuthorize("@ss.hasPermi('system:borrow:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(moduleBorrowService.selectModuleBorrowById(id));
    }

    /**
     * 新增借阅管理
     */
    // @PreAuthorize("@ss.hasPermi('system:borrow:add')")
    @Log(title = "借阅管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ModuleBorrow moduleBorrow) {
        String id = generateAutoIncrementString();
        moduleBorrow.setId(id);
        return toAjax(moduleBorrowService.insertModuleBorrow(moduleBorrow));
    }

    /**
     * 修改借阅管理
     */
    // @PreAuthorize("@ss.hasPermi('system:borrow:edit')")
    @Log(title = "借阅管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ModuleBorrow moduleBorrow) {
        return toAjax(moduleBorrowService.updateModuleBorrow(moduleBorrow));
    }

    @PostMapping("/updateBorrow")
    public AjaxResult updateBorrow(@RequestBody ModuleBorrow moduleBorrow) {
        return toAjax(moduleBorrowService.updateModuleBorrow(moduleBorrow));
    }

    /**
     * 删除借阅管理
     */
    // @PreAuthorize("@ss.hasPermi('system:borrow:remove')")
    @Log(title = "借阅管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {

        return toAjax(moduleBorrowService.deleteModuleBorrowByIds(ids));
    }

    // @PreAuthorize("@ss.hasPermi('system:borrow:remove')")
    @PostMapping("/deleteBorrow")
    public AjaxResult deleteBorrow(@RequestBody StringId stringId) {
        if (stringId.getIds() != null) {
            String[] ids = stringId.getIds();
            return toAjax(moduleBorrowService.deleteModuleBorrowByIds(ids));
        } else {
            String id = stringId.getId();
            return toAjax(moduleBorrowService.deleteModuleBorrowById(id));
        }

        // return toAjax(moduleBorrowService.deleteModuleBorrowByIds(ids));
    }

    /**
     * 获取借阅管理详细信息
     */
    // @PreAuthorize("@ss.hasPermi('system:borrow:query')")
    @GetMapping(value = "/getBorrowDatas/{year}")
    public Map<Object, Object> getBorrowDatas(@PathVariable("year") Integer year) {
        Map<Object, Object> ansMap = new HashMap<Object, Object>();
        // TODO
        // 1.get this year borrow datas
        List<ModuleBorrow> borrowDatas = moduleBorrowService.findByYear(year);
        // 2.stat month numbers
        int[] monthStat = moduleBorrowService.getMonthStat(borrowDatas, year);
        String[] month = { "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" };
        // 3.push datas
        ansMap.put("month", month);
        ansMap.put("monthStat", monthStat);
        return ansMap;
    }

    // public static String generateAutoNumber() {
    // SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    // String todayDate = dateFormat.format(new Date());
    // // Check if it's a new day, and reset the dailyCounter if necessary
    // if (!todayDate.equals(currentDate)) {
    // currentDate = todayDate;
    // dailyCounter = 1;
    // } else {
    // dailyCounter++;
    // }
    // // Create the auto number
    // return currentDate + PREFIX + dailyCounter;
    // }

    public static String generateAutoIncrementString() {
        String currentDate = new SimpleDateFormat(DATE_FORMAT).format(new Date());
        int lastIncrement = getLastIncrement();

        return currentDate + "/1-" + lastIncrement;
    }

    private static int getLastIncrement() {
        int lastIncrement = 0;

        try (BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH))) {
            String line = reader.readLine();
            if (line != null) {
                lastIncrement = Integer.parseInt(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Increment and update the file
        lastIncrement++;
        updateLastIncrement(lastIncrement);

        return lastIncrement;
    }

    private static void updateLastIncrement(int lastIncrement) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_PATH))) {
            writer.write(Integer.toString(lastIncrement));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
